package com.yunhe.controller;


import com.yunhe.dao.DepartmentDao;
import com.yunhe.dao.EmployeeDao;
import com.yunhe.pojo.Department;
import com.yunhe.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model){

        // 查出所有的员工
        Collection<Employee> employees = employeeDao.getAll();

        // 把所有员工放入model中
        model.addAttribute("emps",employees);

        return "emp/list";
    }

    // 去员工的添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model){
        // 查询所有部门的信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);

        return "emp/add";
    }

    // 员工添加页面
    @PostMapping("/emp")
    public String addEmp(Employee employee){

        employeeDao.save(employee);
        return "redirect:/emps";
    }

    // 去员工的修改页面
    @GetMapping("/emp/{id}")
    //@PathVariable是spring3.0的一个新功能：接收请求路径中占位符的值
    public String toUpdateEmp(@PathVariable("id")Integer id,Model model){

        // 查出原来的数据
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);

        // 查询所有部门的信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);

        return "emp/update";
    }
    // 员工修改页面
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeDao.save(employee);

        return "redirect:/emps";
    }

    // 员工删除
    @GetMapping("/delEmp/{id}")
    public String deleteEmp(@PathVariable("id")Integer id){

        employeeDao.delete(id);
        return "redirect:/emps";
    }

    // 退出登录
    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }

}
